package com.wnx.job.modules.pms.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnx.job.domain.CascadeNode;
import com.wnx.job.domain.IndustryNode;
import com.wnx.job.modules.pms.mapper.PmsIndustryMapper;
import com.wnx.job.modules.pms.model.PmsIndustry;
import com.wnx.job.modules.pms.service.PmsIndustryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangnaixing
 * @since 2021-12-17
 */
@Service
public class PmsIndustryServiceImpl extends ServiceImpl<PmsIndustryMapper, PmsIndustry> implements PmsIndustryService {
    @Resource
    private PmsIndustryMapper industryMapper;

    /**
     * 获取行业树
     * @return
     */
    @Override
    public List<CascadeNode> getIndustryTree() {
        List<PmsIndustry> industryList = industryMapper.selectList(null);
        //转树状结构
        List<IndustryNode> result = industryList.stream()
                .filter(industry -> industry.getParentId().equals(0L))
                .map(industry -> buildTreeIndustry(industry, industryList))
                .collect(Collectors.toList());

        //实体转DTO
        return convert(result);
    }


    //实体转DTO
    private List<CascadeNode> convert(List<IndustryNode> industryNodes) {

        List<CascadeNode>  industryVoList = new ArrayList<CascadeNode>();
        industryNodes.forEach(p -> {

            CascadeNode vo = new CascadeNode();
            vo.setLabel(p.getName());
            vo.setValue(p.getId());



            List<IndustryNode> sonIndustryList = p.getChildren();
            if (sonIndustryList != null && sonIndustryList.size() > 0) {
                vo.setChildren(convert(sonIndustryList));
            }

            industryVoList.add(vo);
        });

        return industryVoList;
    }


    /**
     * 将权限转换为带有子级的权限对象
     * 当找不到子级权限的时候map操作不会再递归调用covert
     */
    private IndustryNode buildTreeIndustry(PmsIndustry permission, List<PmsIndustry> permissionList) {
        IndustryNode node = new IndustryNode();

        BeanUtils.copyProperties(permission, node);
        List<IndustryNode> children = permissionList.stream()
                .filter(subPermission -> subPermission.getParentId().equals(permission.getId()))
                .map(subPermission -> buildTreeIndustry(subPermission, permissionList))
                .collect(Collectors.toList());

        node.setChildren(children);
        return node;
    }
}
